package com.echo.code.demo;

import lombok.extern.log4j.Log4j2;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * Created by baiyp on 2019/05/16.
 */
@WebServlet(name = "get", urlPatterns = "/get", initParams = {@WebInitParam(name = "language", value = "english")})
@Log4j2
public class GetServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        log.info("-------------");
        log.info("RequestURI is {}", req.getRequestURI());
        log.info("RequestURL is {}", req.getRequestURL());
        log.info("-------------");
        log.info("LocalAddr is {}", req.getLocalAddr());
        log.info("LocalName is {}", req.getLocalName());
        log.info("LocalPort is {}", req.getLocalPort());
        log.info("-------------");
        log.info("RemoteAddr is {}", req.getRemoteAddr());
        log.info("RemoteHost is {}", req.getRemoteHost());
        log.info("RemotePort is {}", req.getRemotePort());
        log.info("RemoteUser is {}", req.getRemoteUser());
        log.info("-------------");
        log.info("ServerName is {}", req.getServerName());
        log.info("ServerPort is {}", req.getServerPort());
        log.info("ServletPath is {}", req.getServletPath());
        log.info("-------------");
        ServletContext sc = req.getServletContext();
        log.info("ContextPath is {}", sc.getContextPath());
        log.info("Log4j RealPath is {}", sc.getRealPath("log4j2.xml"));
        log.info("-------------");
        String age = sc.getInitParameter("age");
        log.info("parameter age is {}", age);
        ServletConfig config = getServletConfig();
        String language = config.getInitParameter("language");
        log.info("parameter language is {}", language);
        log.info("-------------");
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(sc);
        if (Objects.nonNull(wac)) {
            Log4jExample log4j = wac.getBean(Log4jExample.class);
            log4j.printLog("echo");
        }
        log.info("-------------");
        log.warn("dispatching...");
        RequestDispatcher rd = req.getRequestDispatcher("/WEB-INF/upload.jsp");
        rd.forward(req, resp);
        // resp.sendRedirect("index.jsp");
    }
}